import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import router from '@/router'
import { login } from '@/api/user.js'
import md5 from 'md5'
// import { TOKEN } from '@/constant/index.js'
import { ElMessage } from 'element-plus'
import { setTimeStamp, isCheckTimeout } from '@/utils/auth.js'
import { usePermissionStore } from './permission'

export const useUserStore = defineStore(
  'userStore',
  () => {
    const token = ref('')
    const userId = ref('')
    const conversationId = ref('')
    const Login = async (userInfo) => {
      const { username, password } = userInfo
      if (username !== 'admin' || password !== '123456') {
        ElMessage.error('用户名或密码错误!')
        return
      }
      // console.log('密码正确');
      // const { jwt } = await login({
      //   username,
      //   password: md5(password)
      // })
      // ElMessage({
      //   message: '登录成功',
      //   type: 'success',
      //   duration: 1000
      // })
      token.value = '123456'
      userId.value = Math.random().toString(36).slice(-8)
      // // 保存登录时间
      // setTimeStamp()
      // console.log(token.value);
    }
    const Logout = () => {
      const currentRoute = router.currentRoute.value.fullPath
      token.value = ''
      userId.value = ''
      conversationId.value = ''
      const permissionStore = usePermissionStore()
      permissionStore.removeRoutes()
      if (isCheckTimeout()) {
        router.push(`/login?redirect=${currentRoute}`)
      } else {
        router.push('/login')
      }
    }

    return { token, userId, conversationId, Login, Logout }
  },
  {
    persist: {
      paths: ['token', 'userId', 'conversationId']
    }
  }
)
